﻿using System.Text;
using BBCode.Tags;
using BBCode.Template;

namespace BBCode.Nodes
{
    /// <summary>
    /// BBCode Node that supports Youtube videos
    /// </summary>
    public class BBCodeYoutube : BBCode
    {
        #region constructors

        public BBCodeYoutube(ITag tag, string text, NodeIndex nodeIndex, string opening, string closing)
            : base(tag, text, nodeIndex, opening, closing)
        {
        }

        #endregion

        /// <summary>
        /// Prints the specific Node.
        /// </summary>
        /// <param name="shouldAutoParseLinks">if set to <c>true</c> [should auto parse links].</param>
        /// <returns></returns>
        public override string Print(bool shouldAutoParseLinks = true)
        {
            var textBuilder = new StringBuilder(Text);

            //Remove the opening and closing
            textBuilder.Remove(0, Opening.Length);
            textBuilder.Remove(textBuilder.Length - Closing.Length, Closing.Length);

            //Get the template, fill it and process it!.)))
            switch (Tag.ParseType)
            {
                case ParseType.Clean:
                    //Clean the node, leaving the innertext
                    return textBuilder.ToString();
                case ParseType.Remove:
                    //Remove it ALL!
                    return string.Empty;
                default:
                    //Youtube specific!
                    var indexOfUrl = textBuilder.ToString().ToLower().IndexOf("watch?v=");
                    textBuilder.Remove(0, indexOfUrl + 8);

                    //Default is always to print it as it should be printed!
                    var template = Tag.GetTemplate();
                    template["INNERTEXT"] = textBuilder;

                    return template.Process();
            }
        }
    }
}